import { Toast } from "antd-mobile"
import { list } from "postcss"
import { reqcartadd, reqgetgoodsinfo } from "../../http/api"
const initState = {
    //获取商品分类
    list: [],
    isshow:false,
    pre: "http://localhost:1000",
    //数量
    num:1,


}

const types = {
    //修改types
    CHANGE_CATE: "CHANGE_CATE",
    //修改isshow
    CHANG_ISSHOW:"CHANGE_ISSHOW",
    //修改num
    CHANGE_NUM:"CHANGE_NUM"
}

const reducer = (state = initState, action) => {
    //修改cate
    switch (action.type) {
        //修改cate
        case types.CHANGE_CATE:
            return {
                ...state,
                list: action.list
            }
        //修改isshow
        case types.CHANG_ISSHOW:
            return{
                ...state,
                isshow:action.isshow
            }
        //修改num
        case types.CHANGE_NUM:
            return{
                ...state,
                num:action.num
            }
        default:
            return state
    }
}

export const actions = {
    //修改cate
    changeList: list => ({ type: types.CHANGE_CATE, list }),
    //修改isshow
    changeIsshow:isshow=>({type:types.CHANG_ISSHOW,isshow}),
    //修改num
    changeNumm:num=>({type:types.CHANGE_NUM,num}),
    changeNum:(num)=>(dispatch,getState)=>{
        if(num<1){
            return
        }
        dispatch(actions.changeNumm(num))
    },
    //获取cate
    reqCate: (e) => (dispatch, getState) => {
        reqgetgoodsinfo({id:e}).then(res => {
            if (res.data.code == 200) {
                dispatch(actions.changeList(res.data.list))
            }
        })
    },
    //加入购物车
    reqShop:(e)=>(dispatch,getState)=>{
        let uid = JSON.parse(sessionStorage.getItem("info")).uid
        let type = (e.location.pathname).substr((e.location.pathname).lastIndexOf("=")+1,1)
        let goodsid = e.match.params.id
        let num = e.num
        reqcartadd({uid,type,goodsid,num}).then(res=>{
            if(res.data.code==200){
                Toast.show({
                    content:res.data.msg,
                })
                dispatch(actions.changeIsshow(false))
            }
        })
    }
}

export const getList = state => state.detail.list
export const getPre = state => state.detail.pre
export const getIsshow = state => state.detail.isshow
export const getNum = state=>state.detail.num

export default reducer;